package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.ocr

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication

import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doUploadImage
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.user.mainProcessFormat
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.imageUtil.ImageConvert
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class ProofGhanaOcrViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<ProofGhanaOcrTypeResult>()
    val pageDetailResult: LiveData<ProofGhanaOcrTypeResult> = _pageDetailResult

    private val _mainProcessResult = MutableLiveData<ProofGhanaOcrMainProcessResult>()
    val mainProcessResult: LiveData<ProofGhanaOcrMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<ProofGhanaOcrNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<ProofGhanaOcrNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    var isPickFront: Boolean = true

    /**
     * 切换ocr类型
     */
    fun selectType(type: Int = 0) {
        _pageDetailResult.value = ProofGhanaOcrTypeResult(type = type)
    }

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = ProofGhanaOcrMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                _mainProcessResult.value =
                    ProofGhanaOcrMainProcessResult(error = errMsg)
            }
        })
    }

    /**
     * 上传图片
     */
    private fun uploadImage(filePath: String, type: Int = 0) {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>()
        action["filePath"] = filePath
        action["cardType"] = when (type) {
            0 -> "IDCARD"
            1 -> "DRIVING"
            else -> "PASSPORT"
        }

        context.doUploadImage(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val url = obj.optString("url")
                if (url.isNotBlank()) {
                    uploadImageResult(url, type)
                } else {
                    uploadImageResult(null, type)
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                uploadImageResult(null, type, errMsg)
            }
        })
    }

    /**
     * 保存ocr信息
     */
    fun saveOcrInfo() {
        _loadingResult.value = true
        val frontImageUrl = _pageDetailResult.value?.frontPicUrl ?: ""
        var backImageUrl = _pageDetailResult.value?.backPicUrl ?: ""
        val type = _pageDetailResult.value?.type ?: 0
        if (type == 2) {
            backImageUrl = "https://passport_back.jpg"
        }
        if (frontImageUrl.isBlank() or backImageUrl.isBlank()) {
            _loadingResult.value = false
            _mainProcessResult.value =
                ProofGhanaOcrMainProcessResult(error = "Please upload the licenses")
            return
        }

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "lslb0UDLLZQxmdjHjfA"
        action["cardImgUrl"] = frontImageUrl
        action["cardBackImgUrl"] = backImageUrl
        action["cardType"] = when (_pageDetailResult.value?.type) {
            1 -> {
                "DRIVING"
            }
            2 -> {
                "PASSPORT"
            }
            else -> {
                "IDCARD"
            }
        }

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                mainProcess()
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                _mainProcessResult.value =
                    ProofGhanaOcrMainProcessResult(error = errMsg)
            }
        })
    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormat(fromProof = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                ProofGhanaOcrNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }

    /**
     * 处理图片uri
     */
    @SuppressLint("Recycle")
    fun handlePickImageResult(context: Context, result: Uri?) {
        try {
            result?.let {
                val path = imageUriToLocalFile(context, it)
                //压缩图片
                ImageConvert.startConvertImage(File(path)) { localPath, thumpImg ->
                    updateImageResult(localPath, thumpImg)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 处理图片path
     */
    fun handleTakePictureResult(result: String?) {
        try {
            result?.let {
                val localPath = it
                val thumpImg = imagePathToBitmap(localPath)
                updateImageResult(localPath, thumpImg)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 上传图片回显
     */
    private fun uploadImageResult(url: String?, type: Int = 0, error: String? = null) {
        try {
            var frontPicUrl = _pageDetailResult.value?.frontPicUrl
            var frontPicPath = _pageDetailResult.value?.frontPicPath
            var frontPicBitmap = _pageDetailResult.value?.frontPicBitmap

            var backPicUrl = _pageDetailResult.value?.backPicUrl
            var backPicPath = _pageDetailResult.value?.backPicPath
            var backPicBitmap = _pageDetailResult.value?.backPicBitmap

            if (isPickFront) {
                frontPicUrl = url
            } else {
                backPicUrl = url
            }

            _pageDetailResult.value = ProofGhanaOcrTypeResult(
                type = type,

                frontPicUrl = frontPicUrl,
                frontPicPath = frontPicPath,
                frontPicBitmap = frontPicBitmap,

                backPicUrl = backPicUrl,
                backPicPath = backPicPath,
                backPicBitmap = backPicBitmap,

                error = error
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 更新图片显示
     */
    private fun updateImageResult(localPath: String, thumpImg: Bitmap) {
        try {
            val type = _pageDetailResult.value?.type ?: 0
            var frontPicUrl = _pageDetailResult.value?.frontPicUrl
            var frontPicPath = _pageDetailResult.value?.frontPicPath
            var frontPicBitmap = _pageDetailResult.value?.frontPicBitmap

            var backPicUrl = _pageDetailResult.value?.backPicUrl
            var backPicPath = _pageDetailResult.value?.backPicPath
            var backPicBitmap = _pageDetailResult.value?.backPicBitmap

            if (isPickFront) {
                frontPicPath = localPath
                frontPicBitmap = thumpImg

            } else {
                backPicPath = localPath
                backPicBitmap = thumpImg
            }

            _pageDetailResult.value = ProofGhanaOcrTypeResult(
                type = type,

                frontPicUrl = frontPicUrl,
                frontPicPath = frontPicPath,

                backPicPath = backPicPath,
                backPicUrl = backPicUrl,

                frontPicBitmap = frontPicBitmap,
                backPicBitmap = backPicBitmap
            )

            // 上传图片
            uploadImage(filePath = localPath, type)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun imageUriToLocalFile(
        context: Context,
        contentURI: Uri
    ): String {
        try {
            println(contentURI.path)

            val imgDir = "${
                ProjectApplication.context.applicationContext.filesDir
            }${File.separator}${ProjectApplication.mProduct}_IAGS"

            val dirFile = File(imgDir)
            if (!dirFile.exists()) {
                dirFile.mkdirs()
            }

            val outFilePath = "$imgDir/${System.currentTimeMillis()}.jpg"
            val imgInputStream: InputStream =
                context.contentResolver.openInputStream(contentURI) ?: return ""
            val outFile = File(outFilePath)
            val buffer = ByteArray(1024)
            var len: Int
            val fos = FileOutputStream(outFile)
            while (imgInputStream.read(buffer).also { len = it } != -1) {
                fos.write(buffer, 0, len)
            }
            fos.flush()
            fos.close()
            imgInputStream.close()
            return outFilePath
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun imagePathToBitmap(filePath: String?): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(filePath, options)
    }
}